package com.molichuxing.framework.utils;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class IpUtil {
	private static final Logger logger = LoggerFactory.getLogger(IpUtil.class);

	/**
	 * 获取本机Ip
	 * 
	 * 通过 获取系统所有的networkInterface网络接口 然后遍历 每个网络下的InterfaceAddress组。 获得符合
	 * <code>InetAddress instanceof Inet4Address</code> 条件的一个IpV4地址
	 * 
	 * @return
	 */
	@SuppressWarnings("rawtypes")
	public static String localIp() {
		String ip = null;
		Enumeration allNetInterfaces;
		try {
			allNetInterfaces = NetworkInterface.getNetworkInterfaces();
			while (allNetInterfaces.hasMoreElements()) {
				NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
				List<InterfaceAddress> InterfaceAddress = netInterface.getInterfaceAddresses();

				for (InterfaceAddress add : InterfaceAddress) {
					InetAddress Ip = add.getAddress();
					if (Ip != null && Ip instanceof Inet4Address) {
						ip = Ip.getHostAddress();
					}
				}

			}
		} catch (SocketException e) {
			logger.error("获取本机Ip失败:异常信息:" + e.getMessage());
		}
		return ip;
	}

	/**
	 * 获取请求的IP地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		// 如果客户端经过多级反向代理，则X-Forwarded-For的值并不止一个，而是一串IP值，
		// 取X-Forwarded-For中第一个非unknown的有效IP字符串即为用户真实IP
		String ipResult = getIp(ip);
		if (ipResult != null) {
			return ipResult;
		}

		ip = request.getHeader("Proxy-Client-IP");
		ipResult = getIp(ip);
		if (ipResult != null) {
			return ipResult;
		}
		ip = request.getHeader("WL-Proxy-Client-IP");
		ipResult = getIp(ip);
		if (ipResult != null) {
			return ipResult;
		}
		ip = request.getRemoteAddr();
		ipResult = getIp(ip);
		if (ipResult != null) {
			return ipResult;
		}
		return "";
	}

	private static String getIp(String ips) {
		if (StringUtils.isBlank(ips)) {
			return null;
		}
		String regValidatorIp = "^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$";
		String[] tokens = ips.split(",");
		for (String s : tokens) {
			if (s.trim().matches(regValidatorIp)) {
				return s.trim();
			}
		}
		return null;
	}
}
